// Conf file name must be conf.json at the root of the module
//Config file format: [{"id": <id>, "params" : { } }, {"id": <id>, "params" : { } }]
var fs = require('fs');

// fonction pour rajouter une config dans un fichier (existant ou non)
// ecraser une config deja existante


// fonction pour get une config par id


function ConfigModule(moduleName) {
	moduleName = moduleName;
	confName = 'conf.json';
	serverRoot = './';

//Private


//Public
	this.get = function(idModule, callback) {
		fs.readFile(serverRoot + 'modules/' + moduleName + '/' + confName, 'utf-8', function(error, file) {
			var conf = {};
			if (!error) {
				var config = JSON.parse(file);
				
				for (var i = 0; i < config.length; i++) {
					if (config[i].id == idModule) {
						conf = config[i].params;
						break;
					}
				}

				callback(error, conf);
			} else {
				console.log(error);
				callback(error, conf)
			}

		});
	}

	this.set = function(idModule, params, callback) {
		var fileName = serverRoot + 'modules/' + moduleName + '/' + confName;
	
		var writeConf = function(configs) {
				var confInstance = {};
				confInstance["id"] = idModule;
				confInstance["params"] = params;
				
				var found = null;
				for (var i=0;i<configs.length; i++) {
					if (configs[i].id == idModule) {
						found = configs[i].params;
						break;
					}
				}
				
				if (found == null) {
					configs.push(confInstance);
				} else {
				
					// replace existing keys by the new ones
					for (var key in params) {
						found[key] = params[key];
					}
					configs[i].params = found;
				}
				fs.writeFile(fileName, JSON.stringify(configs), 'utf-8', callback);
		}
	
		fs.readFile(fileName, 'utf-8', function(error, file) {

			if (!error) {
				var configs = JSON.parse(file);
				writeConf(configs);

			} else {
				console.log("Can't read file "+fileName+" , creating it.");
				var configs = [];
				writeConf(configs);
			}

		});

	}
}

exports.ConfigModule = ConfigModule;

